<template>
    <el-form label-width="120px" class="form_box">
        <el-form-item label="选择公众号" required>
            <OfficialAccounts
                :public-data="{ id: form.official_account_id, pageType: '' }"
                @submit="v => v && (form.official_account_id = v)" />
        </el-form-item>
        <el-form-item label="草稿标题" required>
            <el-input v-model="form.draft_title" maxlength="15" :show-word-limit="true" placeholder="请输入标题名称" />
        </el-form-item>
        <!-- 图文 -->
        <template v-if="!['2', '3', '4', '5'].includes(route.query.imgTextType)">
            <el-form-item label="标题" required>
                <el-input
                    v-model="form.content[active].article_title"
                    maxlength="42"
                    :show-word-limit="true"
                    placeholder="请输入标题名称" />
            </el-form-item>
            <el-form-item label="作者">
                <el-input
                    v-model="form.content[active].author"
                    maxlength="8"
                    :show-word-limit="true"
                    placeholder="请输入作者名称" />
            </el-form-item>
            <el-form-item label="正文" required>
                <TinymceEditor v-model="form.content[active].content" :config="config" />
            </el-form-item>
            <el-form-item label="封面" required>
                <UploadImg
                    button-name="选择封面"
                    :rule="{ type: '.jpg, .png', unit: 'KB', size: 64 }"
                    :url="form.content[active].cover"
                    @submit="v => (form.content[active].cover = v)" />
                <div class="text">图片支持JPG、PNG格式，大小64KB以内，建议宽高比为1：1，尺寸200px*200px。</div>
            </el-form-item>
            <el-form-item label="摘要">
                <el-input
                    v-model="form.content[active].digest"
                    type="textarea"
                    maxlength="120"
                    :show-word-limit="true"
                    :rows="4"
                    placeholder="选填，摘要会在订阅消息、转发链接等文章外的场景显露，帮助读者快速了解内容，如不填写则默认抓取正文千54字" />
            </el-form-item>
            <el-form-item label="原文链接" :required="form.content[active].source_switch == 1">
                <el-switch v-model="form.content[active].source_switch" :active-value="1" :inactive-value="2" />
            </el-form-item>
            <el-form-item v-if="form.content[active].source_switch == 1">
                <el-input v-model="form.content[active].source_url" placeholder="请输入原文链接" />
            </el-form-item>
        </template>
        <!-- 音频 -->
        <el-form-item v-if="route.query.imgTextType == '4'" label="上传音频" required>
            <UploadImg
                button-name="上传音频"
                type-name="音频"
                :rule="{ type: '.mp3, .amr', unit: 'MB', size: 2 }"
                :url="form.content[active]?.link"
                @submit="v => (form.content[active].link = v)" />
            <div class="desc">大小不超过2M，长度不超过60S，支持AMR/MP3格式。</div>
        </el-form-item>
        <!-- 文本 -->
        <el-form-item v-if="route.query.imgTextType == '2'" label="文本内容" required>
            <el-input
                v-model="form.content[active].text"
                type="textarea"
                maxlength="300"
                :show-word-limit="true"
                :rows="4"
                placeholder="从这里开始输入文字" />
        </el-form-item>
        <!-- 图片 -->
        <el-form-item v-if="route.query.imgTextType == '5'" label="上传图片">
            <div class="imgs_box">
                <template v-for="(item, index) in form.content[active]?.link?.length + 1" :key="item">
                    <div v-if="index != 9" class="item">
                        <UploadImgs
                            :url="form.content[active]?.link[index]"
                            btn-name="上传图片"
                            :rule="{ type: '.jpg, .png, .jpeg, .gif', unit: 'MB', size: 10 }"
                            @submit="v => (form.content[active].link[index] = v)"
                            @delete="form.content[active]?.link?.splice(index, 1)" />
                        <div v-if="!form.content[active]?.link[index]" class="num">
                            ({{ form.content[active]?.link?.length }}/9)
                        </div>
                    </div>
                </template>
            </div>
        </el-form-item>
    </el-form>
    <Dialog :app-dialog="appDialog">
        <div class="wrapper">
            <el-form>
                <el-form-item class="item_margin">
                    <div class="title">预览链接用于查看文章效果，需关注公众号后才可接收，链接会在短期内失效</div>
                    <el-select
                        v-model="form.preview_wx_user_id"
                        class="wx_select"
                        popper-class="wx_popper"
                        style="width: 100%"
                        multiple
                        filterable
                        allow-create
                        default-first-option
                        :reserve-keyword="true"
                        placeholder="可输入多个微信号回车分隔">
                        <!-- <el-option-group label="发送过的微信号">
              <el-option v-for="item in state.previewWxUserIdList" :key="item" :label="item" :value="item" />
            </el-option-group> -->
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
    </Dialog>
</template>

<script lang="ts" setup>
import OfficialAccounts from '@/components/OfficialAccounts.vue';
import UploadImg from './UploadImg.vue';
import UploadImgs from '@/view/salesleads/salesmanagement/business/components/UploadImgs.vue';
import TinymceEditor from '@/components/TinymceEditor.vue';
import Dialog from '@/components/Dialog.vue';
import {
    createMassOfficialAccount,
    editOfficalDraft,
    getOfficalArticleDetail,
    groupMassOffical,
    againSendMass
} from '@/api/content/channelFootage/officialaccountgraphics';
import { uploadFile2 } from '@/api/common';
import bus from '@/utils/bus';
import { reactive, ref, watch, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { Action } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const { id, copy } = route.query;

const config = ref({
    height: 500,
    menubar: true,
    convert_urls: false,
    paste_data_images: false, // 禁止拖拽上传
    plugins: [
        'advlist autolink lists link image charmap print preview anchor',
        'searchreplace visualblocks code fullscreen',
        'insertdatetime table paste code help hr pagebreak'
    ],
    fontsize_formats: '11px 12px 14px 16px 18px 24px 36px 48px',
    toolbar:
        'undo redo |  fontsizeselect | image  link | bold italic backcolor | \
  alignleft aligncenter alignright alignjustify | \
  bullist numlist outdent indent | removeformat',
    content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
    images_upload_handler: (blobInfo, success, failure) => {
        const file = blobInfo.blob();
        if (file.size > 10 * 1024 * 1024) {
            ElMessage.warning('图片大小不能超过10M');
            success('');
            return;
        }
        uploadFile2({
            file: file,
            fileName: file.name
        }).then(res => {
            success(res.url);
        });
    },
    // 文件上传
    file_picker_callback: (callback, value, meta) => {
        //,,m4v,avi,wmv,rmvb,mov,mpg,mpeg,webm
        let filetype =
            // ".pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4,.mkv, .avi,.wmv, .rmvb,.mov,.mpg,.mpeg,.webm, .jpg, .jpeg, .png, .gif"; //限制文件的上传类型
            '.jpg, .jpeg, .png, .gif';
        switch (meta.filetype) {
            case 'image':
                filetype = '.jpg, .jpeg, .png, .gif';
                break;
            case 'media':
                filetype = '.wav, .mp3';
                break;
            case 'file':
            default:
        }
        const inputElem = document.createElement('input'); //创建文件选择
        inputElem.setAttribute('type', 'file');
        inputElem.setAttribute('accept', filetype);
        inputElem.click();
        inputElem.onchange = () => {
            const upurl = '';
            const file = inputElem.files[0]; //获取文件信息
            // 校验文件类型
            if (!filetype.includes(file.name.split('.').pop().toLowerCase())) {
                ElMessage.warning('文件类型不支持');
                callback('');
                return;
            }
            if (file.size > 10 * 1024 * 1024) {
                ElMessage.warning('图片大小不能超过10M');
                callback('');
                return;
            }
            const fileName = file.name; //获取文件名
            const fileType = fileName.substring(fileName.lastIndexOf('.')); //获取文件类型
            uploadFile2({
                file,
                fileName
            }).then(res => {
                callback(res.url, {
                    text: res.code,
                    title: res.name
                });
            });
        };
    }
});
const state = reactive({
    previewWxUserIdList: []
});
const active = ref(0);
const form = reactive<any>({
    official_account_id: '',
    draft_title: '', //草稿标题/ 多个图文草稿标题一致
    type: 2, //1-保存为草稿 2-预览 3-群发
    preview_wx_user_id: [],
    content: [
        {
            article_title: '',
            author: '',
            content: '',
            digest: '',
            cover: '',
            source_switch: 2,
            source_url: '',
            comment_switch: 1,
            comment_type: 1,
            article_type: 'mpnews', //text
            link: []
        }
    ] //发布nei'tong
});
const onMessage = (msg: string) => ElMessage.success(msg);
const onCreate = async () => {
    // id ? await editOfficalDraft(form) : await createMassOfficialAccount(form)
    if (id && !copy) {
        if (form.type == 1) {
            try {
                await editOfficalDraft(form);
                ElMessage.closeAll();
                router.push('/content/channelFootage/officialaccountgraphics/draftbox');
            } catch (error) {
                if (error.code == 'ECONNABORTED') {
                    ElMessage.error('当前页面素材文件过多，请缩减后再尝试！');
                }
                return;
            }
        }
        if (form.type == 2) {
            const params = { ...form };
            delete params.id;
            try {
                await createMassOfficialAccount(params);
                onMessage('成功发送预览到目标手机微信');
                onCancel();
                return;
            } catch (error: any) {
                if (error.code == 'ECONNABORTED') {
                    ElMessage.error('当前页面素材文件过多，请缩减后再尝试！');
                }
                return;
            }
        }
        if (form.type == 3) {
            try {
                await editOfficalDraft({ ...form, type: 1 });
                await groupMassOffical({ id: form.id });
                ElMessage.closeAll();
                onMessage('群发成功');
                router.push('/content/channelFootage/officialaccountgraphics');
            } catch (error: any) {
                if (error.code == 'ECONNABORTED') {
                    ElMessage.error('当前页面素材文件过多，请缩减后再尝试！');
                } else {
                    router.push('/content/channelFootage/officialaccountgraphics');
                }
                return;
            }
        }
    } else {
        try {
            let resParams = { ...form };
            if (copy) {
                resParams = { ...form, id, form_type: copy };
            }
            await createMassOfficialAccount(resParams);
        } catch (error: any) {
            if (error.code == 'ECONNABORTED') {
                ElMessage.error('当前页面素材文件过多，请缩减后再尝试！');
            }
            router.push('/content/channelFootage/officialaccountgraphics');
            return;
        }
    }
    switch (form.type) {
        case 1:
            ElMessage.closeAll();
            onMessage(`${id && !copy ? '编辑' : '保存'}草稿成功`);
            router.push('/content/channelFootage/officialaccountgraphics/draftbox');
            break;
        case 2:
            onMessage('成功发送预览到目标手机微信');
            form.preview_wx_user_id.forEach(item => {
                state.previewWxUserIdList.includes(item) || state.previewWxUserIdList.push(item);
            });
            onCancel();
            break;
        case 3:
            ElMessage.closeAll();
            onMessage('群发成功');
            router.push('/content/channelFootage/officialaccountgraphics');
            break;
    }
};

// 预览
const onCancel = () => {
    appDialog.visible = false;
    form.preview_wx_user_id = [];
};
// 确定
const appDialogSubmit = async () => {
    if (form.preview_wx_user_id.length === 0) {
        ElMessage.warning('请输入预览的帐号');
        return;
    }
    // 校验微信号格式
    const reg = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/;
    const isWxUser = form.preview_wx_user_id.every(item => reg.test(item));
    if (!isWxUser) {
        ElMessage.warning('请输入正确的微信号');
        return;
    }
    onCreate();
};
const appDialog = reactive({
    visible: false,
    title: '发送预览',
    width: '700px',
    cancel: onCancel,
    submit: appDialogSubmit,
    cancelText: '取消',
    submitText: '确定'
});
const onSubmit = async (type: number) => {
    form.type = type;
    if (form.official_account_id == '') {
        ElMessage.warning('请选择公众号');
        return;
    }
    if (!form.draft_title) {
        ElMessage.warning('请输入草稿标题');
        return;
    }
    // 图文
    if (['0', '1', undefined].includes(route.query.imgTextType)) {
        for (let i = 0; i < form.content.length; i++) {
            if (!form.content[i].article_title) {
                ElMessage.warning('请输入标题');
                bus.emit('toRule', i);
                return;
            }
            if (!form.content[i].content) {
                ElMessage.warning('请输入正文');
                bus.emit('toRule', i);
                return;
            }
            // 字符限制20000
            if (form.content[i].content.length > 20000) {
                ElMessage.warning('字数不能超过20000');
                bus.emit('toRule', i);
                return;
            }
            if (!form.content[i].cover) {
                ElMessage.warning('请选择封面');
                bus.emit('toRule', i);
                return;
            }
            // 正则验证链接
            if (form.content[i].source_switch === 1) {
                if (!form.content[i].source_url) {
                    ElMessage.warning('请输入原文链接');
                    bus.emit('toRule', i);
                    return;
                }
                if (!/^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/.test(form.content[i].source_url)) {
                    ElMessage.warning('请输入正确的原文链接');
                    return;
                }
            }
            // 正则验证a标签是否为外部链接 https://mp.weixin.qq.com/
            const linkReg = /<a.*?href="(.*?)".*?>/g;
            const linkArr = form.content[i].content.match(linkReg);
            if (linkArr) {
                for (let j = 0; j < linkArr.length; j++) {
                    const link = linkArr[j].match(/href="(.*?)"/)[1];
                    if (!/^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/.test(link)) {
                        ElMessage.warning('请输入正确的链接');
                        bus.emit('toRule', i);
                        return;
                    }
                    if (!/^https:\/\/mp.weixin.qq.com/.test(link)) {
                        // ElMessage.warning('很抱歉，此处仅支持插入公众号图文链接')
                        // ElMessage({
                        //   message: '很抱歉，此处仅支持插入公众号图文链接',
                        //   type: 'warning',
                        //   duration: 0,
                        //   showClose: true,
                        //   grouping:true
                        // })
                        await ElMessageBox.alert('很抱歉，此处仅支持插入公众号图文链接', '注意', {
                            confirmButtonText: '确定'
                        });
                        bus.emit('toRule', i);
                        return;
                    }
                }
            }
            // 正则验证是否有外部链接图片
            const reg = /<img.*?(?:>|\/>)/gi;
            const arr = form.content[i].content.match(reg);
            if (arr) {
                for (let j = 0; j < arr.length; j++) {
                    const src = arr[j].match(/src=[\'\"]?([^\'\"]*)[\'\"]?/i);
                    if (src && src[1]) {
                        if (
                            src[1].indexOf('https://img-scrm-dev.keyid.cn/keyid-scrm-server/') === -1 &&
                            src[1].indexOf('https://static.scrm.keyid.cn/keyid-scrm-server/') === -1
                        ) {
                            // ElMessage.warning('不能直接使用外部图片链接')
                            // ElMessage({
                            //   message: '不能直接使用外部图片链接',
                            //   type: 'warning',
                            //   duration: 0,
                            //   showClose: true,
                            //   grouping:true
                            // })
                            await ElMessageBox.alert('不能直接使用外部图片链接', '注意', { confirmButtonText: '确定' });
                            bus.emit('toRule', i);
                            return;
                        }
                    }
                }
            }
        }
    }
    // 文本
    if (route.query.imgTextType === '2') {
        if (!form.content[0].text) {
            ElMessage.warning('请输入内容');
            return;
        }
    }
    // 音频
    if (route.query.imgTextType === '4') {
        if (!form.content[0].link) {
            ElMessage.warning('请上传音频');
            return;
        }
    }
    // 图片
    if (route.query.imgTextType === '5') {
        if (!form.content[0].link.length) {
            ElMessage.warning('请上传图片');
            return;
        }
        if (form.content[0].link.length > 1 && form.type == 2) {
            ElMessage.warning('预览只能上传一张图片');
            return;
        }
    }
    switch (type) {
        case 1:
            //保存草稿
            onCreate();
            break;
        case 2:
            //预览
            appDialog.visible = true;
            break;
        case 3:
            //群发
            onCreate();
            break;
    }
};
// 保存草稿/预览/群发
bus.on('draftboxSubmit', onSubmit);
// 切换
bus.on('handoff', index => {
    active.value = index;
});
bus.on('phoneBtn', type => {
    switch (type) {
        case 'top':
            // 上移
            form.content.splice(active.value - 1, 0, form.content.splice(active.value, 1)[0]);
            active.value--;
            break;
        case 'bottom':
            // 下移
            form.content.splice(active.value + 1, 0, form.content.splice(active.value, 1)[0]);
            active.value++;
            break;
        case 'del':
            // 删除
            form.content.splice(active.value, 1);
            active.value--;
            break;
    }
});
// 新增素材
bus.on('add', type => {
    switch (type) {
        case '0':
            form.content.push({
                article_title: '',
                author: '',
                content: '',
                digest: '',
                cover: '',
                source_switch: 2,
                source_url: '',
                comment_switch: 1,
                comment_type: 1,
                link: [],
                article_type: 'mpnews' //text
            });
            active.value = form.content.length - 1;
            break;
    }
});
bus.on('addyiyou', v => {
    // form.draft_title = res.draft_title
    v.content.forEach((item: any) => {
        if (form.content.length < 8) form.content.push(item);
    });
    active.value = form.content.length - 1;
    // if (form.content.length + v.content.length > 8) ElMessage.warning('最多添加8条图文')
});
watch(
    form,
    val => {
        bus.emit('form', form);
    },
    { deep: true }
);

// 数据回显
const onLook = async () => {
    const type: any = route.query.imgTextType;
    const res = await getOfficalArticleDetail({ id: id });
    Object.keys(form).forEach((key: any) => (form[key] = res[key]));
    form.id = id;
};
onMounted(() => {
    if (id && !route.query.ID) {
        onLook();
    } else {
        bus.emit('form', form);
    }
    switch (route.query.imgTextType) {
        case '0':
            form.content = [
                {
                    article_title: '',
                    author: '',
                    content: '',
                    digest: '',
                    cover: '',
                    source_switch: 2,
                    source_url: '',
                    comment_switch: 1,
                    comment_type: 1,
                    article_type: 'mpnews' //text
                }
            ];
            break;
        case '1':
            form.type = 1;
            break;
        case '2':
            form.content = [
                {
                    text: '',
                    article_type: 'text'
                }
            ];
            break;
        case '3':
            form.type = 3;
            break;
        case '4':
            form.content = [
                {
                    link: '',
                    article_type: 'voice'
                }
            ];
            break;
        case '5':
            form.content = [
                {
                    link: [],
                    article_type: 'image'
                }
            ];
            break;
    }
    if (route.query.ID) {
        getOfficalArticleDetail({ id: route.query.ID }).then((res: any) => {
            form.official_account_id = res.official_account_id;
            form.draft_title = res.draft_title;
            // 1-图文 2-文字 3-视频 4-音频 5-图片
            switch (res.content[0].type) {
                case 1:
                    form.content = res.content;
                    break;
                case 2:
                    form.content = [
                        {
                            text: res.content[0].content,
                            article_type: 'text'
                        }
                    ];
                    break;
                case 3:
                    break;
                case 4:
                    form.content = [
                        {
                            link: res.content[0].media_content.link,
                            article_type: 'voice'
                        }
                    ];
                    break;
                case 5:
                    form.content = [
                        {
                            link: res.content[0].media_content.link,
                            article_type: 'image'
                        }
                    ];
                    break;
            }
        });
    }
    // 选择已有进入
    if (route.query.row) {
        const row = JSON.parse(route.query.row);
    }
});
// 解绑事件
onUnmounted(() => {
    bus.off('add');
    bus.off('draftboxSubmit');
    bus.off('handoff');
    bus.off('phoneBtn');
    bus.off('addyiyou');
});
</script>
<style lang="scss" scoped>
.el-row {
    padding-top: 11px;
}

.form_box {
    padding-bottom: 30px;
}

.wrapper {
    padding: 45px 80px 0;
    min-height: 355px;
    position: relative;
}

.title {
    text-align: center;
}

.imgs_box {
    display: grid;
    grid-template-columns: repeat(auto-fill, 110px);
    grid-gap: 10px;
    grid-auto-rows: 110px;

    .item {
        position: relative;

        .num {
            position: absolute;
            left: 50%;
            top: 65px;
            transform: translateX(-50%);
            cursor: pointer;
            color: #969696;
        }
    }
}

:deep(.wx_select) .el-input__icon {
    display: none;
}

.desc {
    font-size: 12px;
    font-family: STHeitiSC-Light, STHeitiSC;
    font-weight: 300;
    color: #969696;
}
</style>
<style lang="scss">
.wx_popper {
    display: none;
}

.tox-collection__group:nth-child(2) > .tox-menu-nav__js {
    &:nth-child(1) {
        display: none;
    }

    &:nth-child(2) {
        display: none;
    }
}

.el-form-item {
    .text {
        padding-top: 10px;
        font-size: 12px;
        line-height: 1.4;
        color: #999;
    }
}
</style>
